package actions;

import com.opensymphony.xwork2.ActionSupport;
import com.sun.org.apache.bcel.internal.classfile.Code;

import utils.SecurityCode;
import utils.SecurityCode.SecurityCodeLevel;
import utils.SecurityImage;

import java.io.ByteArrayInputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

/**
 * 提供图片验证码
 */
@SuppressWarnings("serial")
public class SecurityCodeImageAction extends ActionSupport implements SessionAware {

	// Struts2中Map类型的session
	private Map<String, Object> session;

	// 图片流
	private ByteArrayInputStream imageStream;

	public ByteArrayInputStream getImageStream() {
		return imageStream;
	}

	public void setImageStream(ByteArrayInputStream imageStream) {
		this.imageStream = imageStream;
	}

	public String execute() throws Exception {

		// 设置浏览器不要缓存此图片
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		// 获取默认难度和长度的验证码
		// 开启Hard模式，可以不区分大小写
		String code = SecurityCode.getSecurityCode(4, SecurityCodeLevel.Hard, false).toLowerCase();
		imageStream = SecurityImage.getImageAsInputStream(code);
		// 放入session中
		session.put("SESSION_SECURITY_CODE", code);
		return SUCCESS;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

}